package vip.liux.backend.infrastructure.textTemplate.spi;

import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;

import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.slf4j.LoggerFactory.getLogger;

public class StandardTemplateRenderingEngine implements TemplateRenderingEngine {

    public static final String ENGINE_NAME = "standard";

    // 匹配以 { 开头、} 结尾，中间包含零个或多个字母、数字或下划线的字符串
    public static final String regex = "\\{\\w*}";

    private static final Logger logger = getLogger(StandardTemplateRenderingEngine.class);

    @Override
    public String render(String template, @Nullable Map<String, Object> model, @Nullable Locale locale, @Nullable Map<String, Object> globalContext) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(template);
        if (model == null) {
            return template;
        }
        while (matcher.find()) {
            String group = matcher.group();//
            String key = group.substring(1, group.length() - 1);
            if (!model.containsKey(key))
                logger.warn("The key {} is not found in the model", key);
            template = template.replace(group, model.get(key).toString());
        }
        return template;
    }

    @Override
    public boolean supports(String renderEngine) {
        return ENGINE_NAME.equalsIgnoreCase(renderEngine);
    }
}
